package cn.labbook.bluetooth.controller;

import cn.labbook.bluetooth.common.ResultDto;
import cn.labbook.bluetooth.util.StringUtils;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import static cn.labbook.bluetooth.constant.ResultConstant.FAIL_CODE;
import static cn.labbook.bluetooth.constant.ResultConstant.SUCCESS_CODE;

public abstract class AbstractController {

    @InitBinder
    private void dateBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        CustomDateEditor editor = new CustomDateEditor(dateFormat, true);
        binder.registerCustomEditor(Date.class, editor);
    }

    protected Date[] stringToDate(String logCreateDate, SimpleDateFormat sdf) {
        if (StringUtils.isNotBlank(logCreateDate)) {
            String[] split = logCreateDate.split(" - ");
            String s0 = split[0].trim() + " 00:00:00";
            String s1 = split[1].trim() + " 23:59:59";

            try {
                Date d0 = sdf.parse(s0);
                Date d1 = sdf.parse(s1);

                Calendar instance = Calendar.getInstance();
                instance.setTime(d1);
                d1 = instance.getTime();

                return new Date[]{d0, d1};

            } catch (ParseException e) {
                e.printStackTrace();
                return null;
            }

        }
        return null;
    }


    public final String forward(String url) {
        return "forward:" + url;
    }

    public final String redirect(String url) {
        return "redirect:" + url;
    }

    public final ResultDto success() {
        return new ResultDto(SUCCESS_CODE, "操作成功");
    }

    public final ResultDto success(Object data) {
        return new ResultDto(SUCCESS_CODE, "操作成功", data);
    }

    public final ResultDto fail() {
        return new ResultDto(FAIL_CODE, "操作失败");
    }

    public final ResultDto fail(String msg) {
        return new ResultDto(FAIL_CODE, msg);
    }
}